trm.nextBus = (function() {
	var _dataURL = 'http://webservices.nextbus.com/service/publicXMLFeed?a=sf-muni';
	var _ajaxURL = '/proxy.php?url=' + encodeURIComponent(_dataURL);
	var _currentRouteTag;
	function _createRouteSelect() {
		$('body').append(' \
			<select id="routeList"> \
			<option value="" selected="selected">SELECT A ROUTE</option> \
			</select> \
			<select id="routeStops" disabled="disabled"> \
			<option value="" selected="selected">SELECT A DIRECTION</option> \
			</select> \
			');
	}
	function _makeAjaxCall(callName) {
		var addlParams, successCallback;
		switch (callName) {
			case 'getRoutes':
				addlParams = '&command=routeList';
				successCallback = function(xml) {
					$(xml).find('route').each(function() {
						$('#routeList').append('<option value="' + $(this).attr('tag') + '">' + $(this).attr('title') + '</option>');
					});
				}
				break;
			case 'getRouteStops':
				addlParams = '&command=routeConfig&r=' + _currentRouteTag;
				successCallback = function(xml) {
					$('#routeStops').removeAttr('disabled');
					$(xml).find('stop').each(function() {
						$('#routeStops').append('<option value="' + $(this).attr('tag') + '">' + $(this).attr('title') + '</option>');
					});
				}
				break;
			default:
				break;
		}
		$.ajax({
			'dataType': 'xml',
			'success': successCallback,
			'type': 'GET',
			'url': _ajaxURL + encodeURIComponent(addlParams)
		});
	}
	function _addRouteSelectHandler() {
		$('#routeList').bind('change', function() {
			var routeTag = $('#routeList').val();
			if (routeTag != '') {
				_currentRouteTag = routeTag;
				_makeAjaxCall('getRouteStops');
			}
		});
	}
	function _setUp() {
		_createRouteSelect();
		_makeAjaxCall('getRoutes');
		_addRouteSelectHandler();
	}
	return {
		setUp: _setUp
	};
})();

$(document).ready(trm.nextBus.setUp);